//
//  ZZMeunLabel.m
//  MenuDemo
//
//  Created by hfzhangzhang on 2018/3/19.
//  Copyright © 2018年 hfzhangzhang. All rights reserved.
//

#import "ZZMeunLabel.h"

@interface ZZMeunLabel()

@property (nonatomic,strong)UIColor *oldBackgroundColor;

@end

@implementation ZZMeunLabel

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self setUp];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self setUp];
    }
    return self;
}
- (void)setUp
{
    self.userInteractionEnabled = YES;
     _oldBackgroundColor = self.backgroundColor;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuControllerWillHide) name:UIMenuControllerWillHideMenuNotification object:nil];
    [self addGestureRecognizer:[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress)]];
}

- (void)menuControllerWillHide{
    [self resignFirstResponder];
    self.backgroundColor = _oldBackgroundColor;
}

- (void)longPress
{
    [self becomeFirstResponder];
   
    self.backgroundColor = [[UIColor grayColor]colorWithAlphaComponent:0.3];
    UIMenuController * menu = [UIMenuController sharedMenuController];
    menu.arrowDirection = UIMenuControllerArrowDown;
    if (menu.isMenuVisible)return;

    UIMenuItem * item1 = [[UIMenuItem alloc]initWithTitle:@"复制" action:@selector(customCopy:)];
    UIMenuItem * item2 = [[UIMenuItem alloc]initWithTitle:@"取消" action:@selector(unSelect:)];
    menu.menuItems = @[item1,item2];
    
    [menu setTargetRect:self.bounds inView:self];
    [menu setMenuVisible:YES animated:YES];
    
}
#pragma mark - 对控件权限进行设置

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if ((self.customOptions&UICustomMeunItem_copy)&&action == @selector(customCopy:)) {
      return YES;
    }
    
    else if ((self.customOptions&UICustomMeunItem_unSelect)&&action == @selector(unSelect:)) {
      return YES;
    }
    return NO;
}

#pragma mark - 方法的实现
- (void)cut:(UIMenuController *)menu
{
    [self customCopy:menu];
    self.text = nil;
}
- (void)customCopy:(UIMenuController *)menu
{
    if (!self.text) return;
    UIPasteboard * paste = [UIPasteboard generalPasteboard];
    paste.string = self.text;
}

- (void)myPaste:(UIMenuController *)menu
{
    UIPasteboard * paste = [UIPasteboard generalPasteboard];
    self.text = paste.string;
}

- (void)unSelect:(UIMenuController *)menu
{
    
}

- (void)dealloc{
    [self resignFirstResponder];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIMenuControllerWillHideMenuNotification object:nil];
}



@end

